from django.shortcuts import render
from django.views import View
from django.db.models import ObjectDoesNotExist
import json
from django.http import JsonResponse
from goods.models import SKU
from django_redis import get_redis_connection
from meiduo_mall.utils.cookiesecret import CookieSecret

# Create your views here.

class CartsView(View):
    """购物车管理"""

    # 添加购物车
    def post(self, request):
        """添加购物车"""

        # 1.提取参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)
        # 2.校验参数
        if not all([sku_id, count]):
            return JsonResponse({'coed': 400, 'errmsg': '缺少参数'})

        try:
            SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist as e:
            return JsonResponse({'code': 400, 'errmsg': 'sku不存在'})

        # 3.业务数据处理－－写数据
        user = request.user
        # 已登录,存入redis
        if user.is_authenticated:
            # 连接redis数据库
            redis_conn = get_redis_connection('carts')
            # 存入redis数据库
            # redis_conn.hmset('carts_%s'%user.id, {sku_id:count})
            redis_conn.hincrby('carts_%s'%user.id, sku_id, count)   # 用hash存sku_id和count
            # 如果选中
            if selected:
                redis_conn.sadd('selected_%s'%user.id, sku_id)  # 用set存selected
            else:
                redis_conn.srem('selected_%s'%user.id, sku_id)  # 没选中就删除
            # 正常响应
            return JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 未登录,存入cookie
        else:
            # 从cookie取出数据
            cookie_str = request.COOKIES.get('carts')
            # 如果cookie有购物车数据
            if cookie_str:
                # 解密，得到用户购物车字典数据
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                # 没有数据，就先定义一个空字典
                cart_dict = {}
            # 如果购物车数据里面已经有这个sku的数据
            if sku_id in cart_dict:
                # 追加数量，修改选中状态
                cart_dict[sku_id]['count'] += count
                cart_dict[sku_id]['selected'] = selected
            else:
                # 直接赋值
                cart_dict[sku_id]={
                    'count': count,
                    'selected': selected
                }
            # 把字典加密成为字符串
            cookie_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            # 设置cookie,存入未登录的购物车数据
            response.set_cookie('carts', cookie_str, max_age=3600*24*14)
            # 正常响应
            return response


    # 展示购物车
    def get(self, request):
        # 1.提取参数
        # 2.校验参数
        # 3.业务数据处理－－读数据
        user= request.user

        cart_dict = {}

        # 已登录
        if user.is_authenticated:

            redis_conn = get_redis_connection('carts')

            redis_carts = redis_conn.hgetall('carts_%s'%user.id)

            redis_selected = redis_conn.smembers('selected_%s'%user.id)

            sku_ids = redis_carts.keys()

            for sku_id in sku_ids:
                sku = SKU.objects.get(pk=sku_id)
                cart_dict[int(sku_id)]={
                    'count': int(redis_carts[sku_id]),
                    'selected': sku_id in redis_selected   # 在里面，返回true
                }


        # 未登录
        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

        # 读取mysql获取sku商品的详细信息，组织响应参数
        cart_skus = []

        sku_ids = cart_dict.keys()
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price,
                'count': cart_dict[sku_id]['count'],
                'selected': cart_dict[sku_id]['selected']
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })


    # 更新购物车
    def put(self, request):
        # 1.提取参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected')

        # 2.校验参数
        if not all([sku_id, count]):
            return JsonResponse({'code': 0, 'errmsg': '缺少必要参数'})

        try:
            SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist as e:
            # 正常响应
            return JsonResponse({'code': 0, 'errmsg': 'sku不存在'})

        # 3.业务数据处理 --修改数据
        user = request.user

        # 已登录－－改redis数据
        if user.is_authenticated:
            # 连接数据库
            redis_conn = get_redis_connection('carts')
            # 用hash存储sku_id和count,,,用user_id作为key,字典｛sku_id:count｝作为value
            redis_conn.hset('carts_%s'%user.id, sku_id, count)
            # 如果商品是选中状态,selected=True,添加一个set, user_id为key,sku_id为value,来标记该商品已经勾选
            if selected:
                redis_conn.sadd('selected_%s'%user.id, sku_id)
            # 如果没勾选，就把这个set去掉，就算数据库里面有这个set,也不会抛出异常
            else:
                redis_conn.srem('selected_%s'%user.id, sku_id)
            # 正常响应
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': {'sku_id': sku_id, 'count': count, 'selected': selected}})
        # 未登录－－改cookie数据
        else:
            # 读前端传来的cookie
            cookie_str = request.COOKIES.get('carts')
            # 如果carts里面有数据，就解密，生成购物车字典数据
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            # 如果carts里面没有数据，生成一个空的字典，准备填充数据
            else:
                cart_dict = {}
            # 如果购物车字典里面已经有这个商品
            if sku_id in cart_dict:
                # 更新数据
                cart_dict[sku_id]['count'] = count
                cart_dict[sku_id]['selected'] = selected
            # 把购物车字典加密成为字符串
            cookie_str = CookieSecret.dumps(cart_dict)
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': {'sku_id': sku_id, 'count': count, 'selected': selected}
            })

            # 将字符串写入cookie
            response.set_cookie('carts', cookie_str)
            # 正常响应
            return response


    # 删除购物车
    def delete(self, request):
        # 1.提取参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        # 2.校验参数
        if not sku_id:
            return JsonResponse({'code': 0, 'errmsg': '缺少参数'})
        try:
            SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist as e:
            return JsonResponse({'code': 0,'errmsg': 'sku不存在'})

        # 3.业务数据处理－－删除数据
        user = request.user
        # 用户存在－－从redis删除数据
        if user.is_authenticated:
            # 链接数据库
            redis_conn = get_redis_connection('carts')
            # 删除sku_id和count
            redis_conn.hdel('carts_%s'%user.id, sku_id)
            # 删除selected
            redis_conn.srem('selected_%s'%user.id, sku_id)
            # 正常响应
            return JsonResponse({'code': 0, 'errmsg': 'ok'})

        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                cart_dict.pop(sku_id)

            cookie_str = CookieSecret.dumps(cart_dict)

            response = JsonResponse({'code': 0, 'errmsg': 'ok'})

            response.set_cookie('carts', cookie_str)

            return response


# 全选购物车
class CartsSelectAllView(View):

    def put(self, request):
        # 1.提取参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected')
        # 2.校验参数
        if not isinstance(selected, bool):
            return JsonResponse({'code': 400, 'errmsg': '缺少参数'})
        # 3.业务数据处理－－修改数据
        user =  request.user
        # 已登录－－修改redis
        if user.is_authenticated:
            # 登陆，把redis购物车全部商品选中
            redis_conn = get_redis_connection('carts')
            # (1)、获取所有sku商品
            # redis_carts = {b'1':b'5', b'2': b'6'}
            redis_carts=redis_conn.hgetall('carts_%s'%user.id)
            # (2)、把所有sku商品的id加入集合
            sku_ids = redis_carts.keys() # [b'1', b'2']
            if selected:
                # 如果勾选，就填入
                redis_conn.sadd('selected_%s'%user.id, *sku_ids)  # *sku_ids对列表进行拆包：(*sku_ids) = (b'1', b'2')
            else:
                # 没有勾选，就删除
                redis_conn.srem('selected_%s'%user.id, *sku_ids)

            return JsonResponse({'code': 0, 'errmsg': 'ok'})
        # 未登录－－修改cookie
        else:
            # (1)、读取cookie购物车字典
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_str = CookieSecret.loads(cookie_str)
            else:
                cart_str = {}
            # (2)、把购物车字典中所有对商品的selected设置未True
            sku_ids = cart_str.keys()
            for sku_id in sku_ids:
                cart_str[sku_id]['selected'] = selected   # 前端传来的selected是True表示全选，为False表示全部取消
            # (3)、加密新字典写入cookie
            cookie_str = CookieSecret.dumps(cart_str)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('carts', cookie_str)
            return response


# 展示简单购物车
class CartsSimpleView(View):
    """商品页面右上角购物车"""
    def get(self, request):
        # 1.提取参数
        # 2.校验参数
        # 3.业务数据处理
        # 已登录
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_cart = redis_conn.hgetall('carts_%s'%user.id)
            redis_selected = redis_conn.smembers('selected_%s'%user.id)
            cart_dict = {}
            sku_ids = redis_cart.keys()
            for sku_id in sku_ids:
                if sku_id in redis_selected:
                    cart_dict[int(sku_id)] = {
                        'count': int(redis_cart[sku_id]),
                        'selected': True
                    }

        # 未登录
        else:
            cookie_str = request.COOKIES.get('carts')
            if cookie_str:
                cart_dict = CookieSecret.loads(cookie_str)
            else:
                cart_dict = {}
            # 如果未选中，就删掉
            sku_ids = list(cart_dict.keys())
            for sku_id in sku_ids:
                if not cart_dict[sku_id]['selected']:
                    cart_dict.pop(sku_id)


        sku_ids = cart_dict.keys()
        cart_skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict[sku_id]['count'],
                'default_image_url': sku.default_image.url
            })


        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })






















































































